#include "thread.h"

Thread::Thread() {

}

Thread::~Thread() {

}

bool Thread::start(int processorAffinity) {
	threadObj = this;

#ifdef _WINDOWS
	threadHandle = CreateThread(0, 0, threadProc, threadObj, 0, &threadID);
	if (threadHandle != NULL) {
		SetThreadAffinityMask(threadHandle, processorAffinity);
		SetThreadIdealProcessor(threadHandle, processorAffinity);
		running = true;
	}
#endif

	return true;
}

void Thread::stop() {
#ifdef _WINDOWS
	running = false;
	// wait for thread to finish
	WaitForSingleObject(this->threadHandle, 5000);

	TerminateThread(this->threadHandle, 0);
#endif
}

unsigned long __stdcall Thread::threadProc(void* ptr) {
	((Thread*)ptr)->run();
	return 0;
}

void Thread::sleep(LONG64 milliseconds) {
#ifdef _WINDOWS
	Sleep((DWORD)milliseconds);
#endif
}

bool Thread::fpsLimit(int fpsLimit, double timePerFrame) {
#ifdef _WINDOWS
	double desiredTimePerFrame = 1.0 / (double)fpsLimit;
	double sleepTime = desiredTimePerFrame - timePerFrame;
	if (sleepTime < 0) {
		return true;
	}
	this->sleep((LONG64)sleepTime * 1000);
	return true;
#endif

	return false;
}

